import { api } from './api'

export interface Board {
  id: number
  title: string
  description: string
  tags: string
  hotness: number
  images: Array<{
    id: number
    img_url: string
    views_count: number
    download_count: number
    created_at: number
  }>
  showUploadOverlay?: boolean
}

export interface UserInfo {
  id: string
  username: string
  nickname: string
  gender: string
  phone: string
  avatar: string
  status: number
  description: string
  artboardCount: number
  followerCount: number
  attentionCount: number
}

export interface UserInfoResponse {
  code: number
  data: UserInfo
  msg: string
  tracers: string
}

export const userApi = {
  // 获取当前用户信息
  async getCurrentUser(): Promise<UserInfo | null> {
    try {
      const response = await api.get<UserInfoResponse>('/api/v1/users/me')
      if (response.code === 0) {
        return response.data
      }
      return null
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  },
  
  // 关注用户
  async followUser(userId: string): Promise<boolean> {
    try {
      const response = await api.post('/api/v1/users/follow', { userId })
      return response.code === 0
    } catch (error) {
      console.error('关注用户失败:', error)
      return false
    }
  },
  
  // 取消关注用户
  async unfollowUser(userId: string): Promise<boolean> {
    try {
      const response = await api.post('/api/v1/users/unfollow', { userId })
      return response.code === 0
    } catch (error) {
      console.error('取消关注用户失败:', error)
      return false
    }
  },
  
  // 获取关注状态
  async getFollowStatus(userId: string): Promise<boolean> {
    try {
      const response = await api.get(`/api/v1/users/follow/status?userId=${userId}`)
      return response.code === 0 && response.data.isFollowing
    } catch (error) {
      console.error('获取关注状态失败:', error)
      return false
    }
  },

  // 获取用户画板数据
  async getUserBoards(): Promise<Board[] | null> {
    try {
      const response = await api.get('/api/v1/users/me/boards')
      if (response.code === 0) {
        return response.data.map((board: Board) => ({
          ...board,
          showUploadOverlay: false
        }))
      }
      return null
    } catch (error) {
      console.error('获取用户画板数据失败:', error)
      return null
    }
  },

  // 上传用户头像
  async updateAvatar(file: File): Promise<{code: number; data: any; msg: string; tracers: string}> {
    try {
      // 创建FormData对象
      const formData = new FormData()
      formData.append('avatar', file)
      
      // 使用统一的api实例发送请求
      const response = await api.post('/api/v1/users/me/avatar', formData)
      return response
    } catch (error) {
      console.error('上传头像失败:', error)
      throw error
    }
  }
}